
/*
*Pool Public Licence version 0.1 or later
*Released on 20th April 2008.
*Any voilations can be repoted at paritosh@wikiocean.net
*What is treated as voilations can be found at www.wikiocean.net/ppl1-voilations* 
******************************************************************************
* The contents of this file are subject Affero GPL v3 and later with additional conditions.
* The additional conditions are to be considered as part of the Affero GPL v3 and later.
* The additional conditions will supersede the Affero GPLv3 and later in case of conflict.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.gnu.org/licenses/agpl.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya.
* created by Paritosh Pungaliya are Copyright (C) Paritosh Pungaliya; All Rights Reserved.
* Contributions are Copyright (C) 2001-2008 Paritosh Pungaliya.

* Objective of the additional terms (license) 
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencie(s).
* 3) To avoid a situation where big corporates or investors can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the openness changes in companies that get Venture Capital funding.)
* (if you agree to this logic I invite you to our group to work together)

* Additional conditions
*  0) Source code will also include
* 	a) data dictionaries, data ontologies which are used to alter the behavior of code or to control           the features of application.
* 	b) Any code generated or derived automatically or manually from this code or logic
*  1) The revenue generated by deploying, implementing , selling services and other activities
*  	 based on this source code should be shared 100%, between the people working on it.
*  2) Capital invested should be given only fixed rate of return or linked to revenue/surplus growth for limited time.
*  3) People working on the project should always have an option to replace the capital provider in full or part with lower cost capital.
*  4) Their should not be any ownership which can be sold as a claim on future profit to be generated from the work of people working on the code.
*  5) Brand thus generated should belong to the group.
*  6) For old and new members revenue sharing should be equal for same work equivalent.
*  7) The share of revenue should be decided by bidding for work before allocation of work within the group.
*  8) Before bidding various method of measuring the work should be clearly defined and published in public domain. Any change in process should also be publised in public domain imediately.
*  9) All data related to to revenue sharing should be published as and when generated in public domain.
*  10) For group of people having size more than 10 people will have to make it open online for others to participate in bids. 
*  11) All people involved in related and sub project will be treated as a group.
*  12) Once this license is being used for a certain code then all and any other software services being provided by the group should complusorilly come under 100% revenue sharing.
*  13) Cross subsidization should not happen under this revenue share, no additional benefit should be drawn from the people, by the employing agency.
*  14) Any position or knowledge or legal structure created relating to people working on code, which adversely affects the spirit of 100% revenue share will be treated as a violation.
*  15) Revenue sharing defined.
*     a) includes direct revenue and also intangible gains like brand, and organization.
*     b) No personal judgment should be involved in judging the distribution of revenue.It has to be pre-defined formula based.
*     c)100% of revenue should be shared before expenses and recievers should have control over what expenses to incur.
*     d)For the work done in any month by contributing group member, working on any project can be given revenue share from the work done by the group, for a maximum of 18 months after that month.
*     e)Revenue should be apportioned to the month in which work is done and not when received.
*  The group fulfilling the above conditions also has to be a wiki ecosystem further defined in www.wekosystem.org or read about Wekosystem at www.wikiocean.net

*  ******************************************************************************
*/  
package control;

import java.sql.ResultSet;
import java.util.Hashtable;

import pool.tablename.Pool;
import User.Uservalidation;
import dbmanager.*;
import timer.ExecutionTimer;
import timer.TimerRecordFile;
import utility.*;


/**
 *  @author ControlClass
 **/
public class Control 
{
	String Username;
	String Password;
	String Message;	
	
	String requestType;
	String version;
	//String process;
	
	Hashtable<Object,Object> ResponseOfMessageParsing = new Hashtable<Object,Object>();
	Hashtable<Object,Object> ResponseOfRequestProcessing = new Hashtable<Object,Object>();
	String msg;
	ResultSet rs;
	DBManager database;
	private RequestParameter reqParam;
	
	/** 
	 * The message send from ControlClass is in the following format, "Username,Message,database".
	 * Here database object is created & through getConnect() of DBManager, connection is created to database. In DBManager class, object of Logger class is created. Also init() of Column class is invoked,  in which FileUtility class' object is created for getting indices of mid,pid,pv,vt,ref which are the fields of property_details table.
	 * When a message is passed, constructor of ControlClass is invoked where username, ie mobile no., message, ie request or order, & database object are passed as parameters. Here replacesspace() of Replacesspace class is also called to trim spaces in the message.  
	 * @param Username as a parmeter of the control class, and is mobile number provided to every users.  
	 * @param Message as a parmeter of the control class, and is any type of message for any table.  
	 * @param database as a parmeter of the control class.
	 **/
	public Control(String Username, String Message,DBManager database)
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		this.database = database;
		this.Username = Username;
		try 
		{
			SpecialCharacter cp1 = new SpecialCharacter();
			int start = cp1.getNextSpChar(0, Message.toCharArray());
			String usernameMessage= Message.substring(start);
			String init = Message.substring(0, start);
			String replacerequest = Replacesspace.replacesspace(usernameMessage);
			if(replacerequest.equals("ERROR"))
				this.Message = replacerequest;
			else
				this.Message  =init + replacerequest;		
			
		} 
		catch (Exception e)
		{
			this.Message  = Replacesspace.replacesspace(Message);
		}
		database.pLog.Logger.append("UserName : "+Username+"\nIncoming Message : "+Message+"\n");
		t.end();
		TimerRecordFile timerFile=new TimerRecordFile("control","Control","Control",t.duration());
	}
	
	/**
	 * In ControlClass class validation of user is done through invoking UserValidation class through messageprocessing. 
	 * @return ResponseOfMessageParsing as a result of parsig 
	 * the input.
	 */
	public Hashtable<Object,Object> messageProcessing()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		try
		{
			Uservalidation validateUser = new Uservalidation(database);
		/*	if(validateUser.validate_User(Username)==false)
			{
				System.out.println("control::ControlClass::messageProcessing()::You are not Authorized User");
				ResponseOfMessageParsing.put("ErrorUser", "TRUE");
				database.pLog.Logger.append("Error : Unauthorized User \n");
				return ResponseOfMessageParsing;
			}*/
			
			//DataInput;
			String parseMessage = Message;
			System.out.println("control::ControlClass::messageProcessing()::Message Obtained in ControlClass is :--> "+Message);
			
			//Parsing Message using dictionary table
			Dictionary dict = new Dictionary(database,Username);
			parseMessage = dict.parse(parseMessage);
			
			if(parseMessage.equalsIgnoreCase("ERROR"))
			{
				ResponseOfMessageParsing.put("Error", "Unable to Parse Input String Please check dictionary");
				return ResponseOfMessageParsing;
			}
			
			//int start = parseMessage.indexOf('*');
			reqParam = new RequestParameter();
			//parseMessage = reqParam.splitRequest(parseMessage);
			parseMessage = reqParam.splitRequest(parseMessage);
			reqParam.setUsername(Username);
			
			if(parseMessage.contains("ERROR"))
			{
				ResponseOfMessageParsing.put("Error", parseMessage);
				return ResponseOfMessageParsing;
			}
			
			requestType = reqParam.getRequest();
			System.out.println("\ncontrol::ControlClass::messageProcessing():: Request Type :"+requestType);
			
			Password = reqParam.getPassword();
			database.pLog.Logger.append("Password : "+Password+"\n");
			
			//USER password VALIDATION 
			try
			{
				if(validateUser.validate_User(Username, Password)==false)
				{
					System.out.println("control::ControlClass::messageProcessing()::You are not Authorized User");
					ResponseOfMessageParsing.put("ErrorUser", "TRUE");
					database.pLog.Logger.append("Error : Unauthorized User \n");
					return ResponseOfMessageParsing;
				}	
			}
			catch(Exception e)
			{
				System.out.println("control::ControlClass::messageProcessing():: Exception : "+e.getMessage());
			}
			
			Message = parseMessage;
			System.out.println("\n\ncontrol::ControlClass::messageProcessing()::Message to forward is : "+Message);
			//ResponseOfMessageParsing =(Hashtable<Object,Object>)requestProcess();
		}
		catch (Exception e) {
			ResponseOfMessageParsing.put("Error", "Unable to Parse Input String");
		}
		t.end();
		TimerRecordFile timerFile=new TimerRecordFile("control","Control","messageProcessing",t.duration());
		return ResponseOfMessageParsing;
	}
	
	/**
	 * In requestProcess() C is a object of the class dynamically binds the classes and interfaces. 
	 * @return ResponseOfRequestProcessing as a the Class object associated with the
	 * class or interface accrding to the request type.
	 * initialize() called through retail interface according to the given request.
	 * It returns hashtable which contains the key ad value pair of the fields, 
	 * which checks whether message contains properties for  that particular 
	 * request or not.
	 **/
	public Hashtable<Object,Object> requestProcess()
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		try
		{
			Class C = Class.forName("retail.tablename."+CapitalChar.makeFirstCharCapital(requestType));
			Pool retail = (Pool) C.newInstance();
			retail.setDatabase(database);
			retail.setRequestParameter(reqParam);
			
			//CALL PROCESS
			//ResponseOfRequestProcessing.putAll(retail.process());
			System.out.println("control::ControlClass::requestProcess()::In RequestProcess");
			retail = null;
			C = null; 
		}
		
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		}
		catch (InstantiationException e) 
		{
			e.printStackTrace();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			ResponseOfRequestProcessing.put("Error", "Unable to Parse Input String");
		}
		System.out.println("control::ControlClass::requestProcess()::Final Response is :-> "+ResponseOfRequestProcessing);
		t.end();
		TimerRecordFile timerFile=new TimerRecordFile("control","Control","requestProcess",t.duration());
		return ResponseOfRequestProcessing;
	}
	
	/**
	 * In main(), database object is created & through that odject make a call to getConnect() method of DBManager, and  
	 * connection is created to database. 
	 * control object of the control class that used to send the request to the respective class.
	 **/
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		ExecutionTimer t = new ExecutionTimer();
		 t.start();
		DBManager database = new DBManager();
		database.getConnect();
		//ControlClass control = new Control("+919922918605","11 master_table add*God1494723146|mobileno:12|city:latur#605",database);
		//Control control = new Control("+919922918605","11 property_details add*God1494723146|process:getrateobjectsell#605",database);
		//Control control = new Control("+919922918605","11 master_table add*sddys|type:item|category:98904673284#605",database);
		//Control control = new Control("+919922918605","11 property_details add*retailervalidation#605",database);
		//Control control = new Control("+919922918605","11 property_details add*\"osc retail new parent \"|type:retailer|Address:Nashik|scope:protected!address#605",database);
		//Control control = new Control("+919922918605","11 master_table add*osscnewf0hchfi1ld325lf1gg1|inheritance:\"osc retail new parent \"!il|mobilno:\"+919922918602\"|Address:\"karve nagar pune \"#605",database);
		//Control control = new Control("+919960613969","11 master_table add*pqr|Qty-555#pqrs",database);
		//Control control = new Control("+919960613969","11 dictionary add*\"11 transaction add\"-F#pqrs",database);
		//Control control = new Control("+919960613969","11 master_table add*Lux6|brand:Lux|quantity:m#pqrs",database);
		//Control control = new Control("+919960613969","11 transaction add*PO>company|xyz-230,AJD600<UOM-gm,AHU200<UOM-kg#pqrs",database);
		//Control control = new Control("+919922918605","11 transaction add*PO<aab|Reference:xyz,acb10,adc20?Reference:200#605",database);
		//Control control = new Control("+919922918605","11 property_details add!report*Atul|name:atul121#605",database);
		//Control control = new Control("+919922918605","11 property_details add*\"DDD\"| city:\"Delhi\" !1| add:\"North\" |mobile:\"+91999\"  #605",database);
		//Control control = new Control("+919922918605","11 dictionary mod ,df $fd  : he $ eh #605",database);
		//Control control = new Control("+919922918605","11 dictionary mod   $eh *\"Hello abc\":ha $df *\"ABC add\" :fd #605",database);
		//Control control = new Control("+919922918605","11 property_details mod*DDD$city:\"Raipur\"$add:\"MAH\"#605",database);
		//Control control = new Control("+919922918605","11 property_details add*\"DDD\" |Item :Shoe  !1 #605",database);
		//Control control = new Control("+919922918605","11 property_details mod*diary$Pages:100|Pages:200#605",database);
		//Control control = new Control("+919922918605","11 property_details mod*\"DDD\" $ Item : Glass |Item : Shoe#605",database);
		//Control control = new Control("+919922918605","11 property_details add * queryA |Path:\"D://Reports//Custom_Reports//\"#605",database);
		//Control control = new Control("+919922918605","11 property_details mod*Lux66223$brand:\"LUX\"|brand:\"Luc\"#605",database);
	    //Control control = new Control("+919922918605","11 master_table add*SSSTTT :City :ShriRamPur |City:Surat |City:Pune#605",database);
		//Control control = new Control("+919922918605","11 property_details add * DMM | name:\"Lucky\" | city:\"Satara\" | add:\"MH\" | mobile:\"+919879252899\" # 605 ",database);
		//Control control = new Control("+919922918605","11 property_details add * DMY555 | emailId:\"xyz@abc.com\"#605",database);
		//Control control = new Control("+919922918605","11 master_table mod * \"Mr. Div V. K. \" , \" Mr. Divyesh V. K. \" #605",database);
		//Control control = new Control("+919922918605","11 master_table mod * student $ Name : Abc | Name : lmn $ Rollno : 25 | Rollno : 20 #605",database);
		//Control control = new Control("+919922918605","11 master_table mod * student $ Name : Abc | Name : lmn $ Rollno : 25 | Rollno : 20 #605",database);
		//Control control = new Control("+919922918605","11 master_table add*Mobile#605",database);
		//Control control = new Control("+919922918605","11 property_details add*Dummymast|emailId:\"xyz@abc.com\"#605",database);
		//Control control = new Control("+919960613969","11 dictionary add*pqr-p*abcd-q#605",database");
		//Control control = new Control("+919960613969","11 transaction mod*PO$1>Arihant#pqrs");
		//Control control = new Control("+919960613969","11 transaction mod*PO$1|pqr-lmn#pqrs");
		//Control control = new Control("+919922918605","11 master_table mod*Lux,luc#605",database);
		//Control control = new Control("+919960613969","11 master_table add*Lux66223|brand:Luc#pqrs",database);
		//Control control = new Control("+919960613969","11 transaction mod*PO$1{Lux-10#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*Autoupdate|Attribute-Attribute#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*autoupdateA|Type-autoupdate|priority-medium|update-yes#pqrs",database);
		//Control control = new Control("+919960613969","11 master_table add* WIKI21d1 | type:attribute #969696", database);
		//Control control = new Control("+919960613969","11 master_table add*FieldlistA|type-fieldlist|field-id|field-seller|field-buyer#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*conditionA|type-condition|FieldList-FieldListA|conditionfield-seller|conditionvalue-company|conditionoperator-=#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*conditionB|type-condition|FieldList-FieldListA|conditionfield-seller|conditionvalue-buyer|conditionoperator-=#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*queryA|Type-query|fieldlist-FieldListA|queryType-select|condition-conditionA#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*queryB|Type-query|fieldlist-FieldListA|queryType-select|condition-conditionB#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*StorageA|Type-storage|Path-\"c:/reports/customReports/\"#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*reportB|Type-report|query-queryA|autoupdate-autoupdateA|storage-StorageA"#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*reportC|Type-report|query-queryB|autoupdate-autoupdateA|storage-StorageA"#pqrs");
		//Control control = new Control("+919960613969","11 master_table add*po|Report-reportB|Report-reportC#pqrs");
		//Control control = new Control("mahendra","nm*\"+919960613969\"|Password-pqr#mahendraxyz",database);
		//Control control = new Control("+919922904553","11 Report add*basic?transaction@yes$buyer^\"=\",\"Trimurti Generals\"#4554",database);
		//Control control = new Control("+919922904553","11 master_table add*\"Dummy_Retailer_s\"|Type:Retailer|Usergroup:Dummy!Buy#605",database);
					
									/*****************Master_table*****************/
		//Control control = new Control("+919922918605","11 master_table add *aaabbb #605",database);
		//Control control = new Control("+919922918605","11 master_table view *aaa44#605",database);
		//Control control = new Control("+919922918605","11 master_table mod ,pkg*pkt#605",database);
		
		//Control control = new Control("+919922918605","11 property_details add *postgres|type:item|city:pune#605",database);
		
		
									/*****************property_details *****************/
		
		//Control control = new Control("+919922918605","11 property_details add  *jfh|thchn:1376544#605",database);
		//Control control = new Control("+919922918605","11 property_details view |type:Storage#605",database);
		//Control control = new Control("+919922918605","11 property_details mod *Color $type:attribute3|type:attribute5#605",database);
		//Control control = new Control("+919922918605","11 property_details Del * fghhhggl | type : 1376544#605",database);
		
	//Control control = new Control("+919922918605","11 property_details mod *postgres$city:Raipur|city:Patna#605",database);

									/*****************transaction *****************/
		
		//Control control = new Control("+919922918602","11 transaction add *po<abb>aaa,ada20?product:item,abb40?product:item#mag",database);//?color:bbbbba?product:adcd1
		//Control control = new Control("+919922918605","11 transaction view @670 #605",database);
		//Control control =new Control("+919960613969","11 transaction mod @667$acc:ADC>acd<abc#605",database);/*E*///
			
								/************** Trans_property_details  *******************/
		
		//Control control = new Control("+919922918605","11 trans_property_details add *5|reference:ag|reference:mnm#605",database);/*E/
		//Control control = new Control("+919922918605","11 trans_property_details view @8|reference:abc#605",database);/*E/
		// Control control = new Control("+919960613969","11 trans_property_details mod *656$Reference:bbbba|Reference:sswd#605",database);/*E*/

								/************** Transaction_details  *******************/
		//Control control = new Control("+919922918605","11 transaction_details add *1,adc64651?color:blckgkkk?product:wdg,adc34?color:blckk#605",database);/*E*/		
		Control control = new Control("+919922918605","11 transaction_details view @670,adb200#605",database);/*E*/
		//Control control = new Control("+919922918605","11 transaction_details mod *656$ada200,ada21#605",database);/*E*/
		
		
								/************** TD_property_details  *******************/
		//Control control = new Control("+919922918605","11 td_property_details add*667,ada20?product:Lux,abb40?product:Rin#605",database);/*E*/
		//Control control = new Control("+919922918605","11 td_property_details mod *667,ada20@product:Parle#605",database);/*E*/ //?product:Lux
		//Control control = new Control("+919922918605","11 td_property_details view @670,adb200?product:Lux#605",database);/*E*/
		
		
								//************** rate_master  *******************/
		//Control control = new Control("+919922918605","11 rate_master add *crunch:10?Buy>piece|HG #605",database);//<\"130707 130751\",\"2007-07-13 \"
		//Control control = new Control("+919922918605","11 rate_master view |VG1 #605",database);
		
						/************** dictionary  *******************/
		//Control control = new Control("+919922918605","11 dictionary add *\"Have a nice day \":aghad#605",database); 
		//Control control = new Control("+919922918605","11 dictionary view :GsdcF#605",database);
		//Control control = new Control("+919922918605","11 dictionary mod ,\"Have a nice day to all \" *\"Have a nice day \"#605",database);
		//Control control = new Control("+919922918605","11 dictionary mod $aghaa :aghad#605",database);
		
		Hashtable<Object, Object> reply = control.messageProcessing();
		if(reply.containsKey("Error")==false)
			control.requestProcess();
		else
			System.out.println(reply + " Please refer the given manual......");
		database.pLog.addLog();
		t.end();
		TimerRecordFile timerFile=new TimerRecordFile("control","Control","main",t.duration());
	}
}